package com.hui.server.service.impl;

import com.hui.server.entity.Admin;
import com.hui.server.service.RoleService;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @BelongsProject: yeb
 * @BelongsPackage: com.hui.server.service
 * @Author: HUI
 * @CreateTime: 2022-04-03 14:51
 * @Description: SpringBoot 2.6 不允许循环依赖，Service注入会调用构造器
 */

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private AdminServiceImpl adminService;

    @Autowired
    private RoleService roleService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Admin admin = adminService.getAdminByUserName(username);
        if (null == admin) throw new UsernameNotFoundException("用户名或密码不正确！");

        if (!admin.isEnabled())throw new UsernameNotFoundException("当前用户没有登录权限，账户已被禁用");
        //设置权限
        admin.setRoles(roleService.getRolesByAdminId(admin.getId()));
        return admin;
    }
}
